package alejandro.castro.extras;

import java.util.LinkedList;
import java.util.List;

import alejandro.castro.abstracts.PlaceableComponent;
import alejandro.castro.asteroid.AsteroidScene;
import alejandro.castro.asteroid.components.Asteroid;
import alejandro.castro.asteroid.components.Shot;

public class ComponentsRemover extends Thread {

	List<Asteroid> removedAsteroids;
	List<Shot> removedShots;

	private static final int REMOVE_RATE = 1000;
	private AsteroidScene scene;	

	public ComponentsRemover(AsteroidScene scene) {
		this.scene = scene;
		removedAsteroids = new LinkedList<Asteroid>();
		removedShots =  new LinkedList<Shot>();
	}
	@Override
	public void run() {
		super.run();
		while(true){
			try {
				this.scene.componentsAdding.acquire();
				
				for (Asteroid asteroid : scene.getAsteroids()) {
					if(isOutOfDisplay(asteroid)){
						removedAsteroids.add(asteroid);
					}
				}
				this.scene.removeAsteroids(removedAsteroids);
				
				for (Shot shot : scene.getShots()) {
					if(isOutOfDisplay(shot)){
						removedShots.add(shot);
					}
				}
				this.scene.removeShots(removedShots);
				
				
				this.scene.componentsAdding.release();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			removedAsteroids.clear();
			removedShots.clear();
			
			
			try {
				sleep(REMOVE_RATE);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	private boolean isOutOfDisplay(PlaceableComponent component) {
		return component.borderBottom() < 0 || //bootom
				component.borderTop() > scene.getGame().getDisplayHeight() || //bootom
				component.borderRight() < 0 || //bootom
				component.borderLeft() > scene.getGame().getDisplayWidth() ; //bootom
	}
}
